package cn.hdu.liang.ch3;

import cn.hdu.liang.ch1.Apple;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class MultiPredicate {
    public static void main(String[] args) {
        List<Apple> inventory = new ArrayList<>();
        inventory.addAll(Arrays.asList(new Apple(80, "green"), new Apple(155, "green"), new Apple(120, "red")));

        //选出非红苹果
        Predicate<Apple> redApple = (Apple apple) -> "red".equals(apple.getColor());
        List<Apple> apples = filter(inventory, redApple.negate());
        System.out.println(apples);

        Predicate<Apple> redAndBigApple = redApple.and(a -> a.getWeight() > 150);
        List<Apple> apples2 = filter(inventory, redAndBigApple);
        System.out.println(apples2);

        Predicate<Apple> redAndBigAppleOrGreen = redAndBigApple.or(a -> "green".equals(a.getColor()));
        List<Apple> apples3 = filter(inventory, redAndBigAppleOrGreen);
        System.out.println(apples3);

    }

    public static <T> List<T> filter(List<T> list, Predicate<T> p) {
        List<T> results = new ArrayList<T>();
        for(T a : list) {
            if(p.test(a)) {
                results.add(a);
            }
        }
        return results;
    }
}
